package com.quan.bookmall.repository;

import com.quan.bookmall.entity.Order;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;

@Repository
public interface OrderRepository extends JpaRepository<Order, Long> {
    
    Page<Order> findByUserId(Long userId, Pageable pageable);
    
    @Query("SELECT o FROM Order o JOIN o.orderItems oi WHERE o.userId = :userId AND " +
           "(:startTime IS NULL OR o.createTime >= :startTime) AND " +
           "(:endTime IS NULL OR o.createTime <= :endTime) AND " +
           "(:bookName IS NULL OR oi.bookName LIKE %:bookName%)")
    Page<Order> findByUserIdAndTimeRangeAndBookName(
            @Param("userId") Long userId,
            @Param("startTime") LocalDateTime startTime,
            @Param("endTime") LocalDateTime endTime,
            @Param("bookName") String bookName,
            Pageable pageable);
    
    @Query("SELECT o FROM Order o JOIN o.orderItems oi WHERE " +
           "(:startTime IS NULL OR o.createTime >= :startTime) AND " +
           "(:endTime IS NULL OR o.createTime <= :endTime) AND " +
           "(:bookName IS NULL OR oi.bookName LIKE %:bookName%)")
    Page<Order> findByTimeRangeAndBookName(
            @Param("startTime") LocalDateTime startTime,
            @Param("endTime") LocalDateTime endTime,
            @Param("bookName") String bookName,
            Pageable pageable);
} 